<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车加减</title>
    <style>
        .count-box {
            width: 200px;
            margin: 20px auto;
            user-select: none;
        }
        .count-box span {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            font-size: 16px;
            border: 1px solid #ccc;
            text-align: center;
        }
        .count-box .count {
            width: 50px;
        }
        .count-box .btn {
            background-color: #ccc;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="count-box">
        <span data-num="-1" class="btn">-</span>
        <span class="count">1</span>
        <span data-num="1" class="btn">+</span>
    </div>
    <script>
        let btns = document.querySelectorAll(".btn")
        let countBox = document.querySelector(".count")
        btns.forEach(btn=>{
            btn.addEventListener("click", function(e){
                let num = parseInt(e.target.dataset.num)
                let curCount = parseInt(countBox.innerText);
                curCount+=num
                if(curCount <0){
                    curCount = 0
                }
                countBox.innerText = curCount;
            })
        })
    </script>
</body>
</html>